'use strict'

let nunjucks = require('nunjucks');

function createEnv(path, opts) {
    path = path || "";
    opts = opts || {};

    let loaderOptions = {
        watch: opts.watch || true,
        noCache: opts.noCache || true
    }

    let envOptions = {
        autoeacapa: opts.autoeacapa || true,
        throwOnUndefined: opts.throwOnUndefined || false
    }
    let loader = new nunjucks.FileSystemLoader("views", loaderOptions);
    let env = new nunjucks.Environment(loader, envOptions);

    if (opts.files) {
        for (let ch in opts.files) {
            env.addFilter(ch, opts.files[ch]);
        }
    }
    return env;
}

module.exports = async (ctx, next) => {
    ctx.render = function (view, model) {
        let env = createEnv();
        ctx.body = env.render(view, model);
    }
    await next();
}

